package com.chaos.eurekaproducer.juc;

import java.util.concurrent.TimeUnit;

/**
 * @author liaopeng
 * @title: InterruptDemo2
 * @projectName eureka-producer
 * @description: 阻塞状态调用Interrupt方法
 * @date 2022/3/12下午9:33
 */
public class InterruptDemo2 extends Thread{

    //中断状态，默认非中断
    volatile boolean stop = false;

    @Override
    public void run() {
        while (!stop) {
            System.out.println("the thread is running");
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                System.out.println("the thread is interrupted");
            }
        }
        System.out.println("exiting under request");
    }

    public static void main(String[] args) throws InterruptedException {
        InterruptDemo2 thread = new InterruptDemo2();
        System.out.println("start thread");
        thread.start();
        TimeUnit.SECONDS.sleep(2);
        System.out.println("asking thread to stop");
        //设置stop为true，
        // 如果thread是非阻塞状态，while循环就会终止，线程也会正常结束，
        // 如果thread是阻塞状态，因为thread无法执行run方法，所以无法正常终止线程，则会抛出InterruptedException，进入catch代码块中
        thread.stop=true;
        //设置线程的中断状态,由于thread处于阻塞状态，所以此时会中断thread的阻塞状态，抛出异常，threa继续运行，发现stop为true，然后正常退出
        thread.interrupt();
        TimeUnit.SECONDS.sleep(3);
        System.out.println("stopping application ");
    }
}
